﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Write.Applications.Commands.RBAC;
using AutoMapper;
using MediatR;
using System.Data;

namespace AuthCenter_API.Write.Applications.CommandHandlers.RBAC
{
    public class MenuUpdCommnadHandler : IRequestHandler<MenuUpdCommnad, APIResult<object>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;

        public MenuUpdCommnadHandler(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(MenuUpdCommnad request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.UpdSuccess;
            result.Message = APIEnum.UpdSuccess.Desc();
            MenuModel menu=_mapper.Map<MenuModel>(request);
            menu.CreateName = "张三";
            menu.CreateTime = DateTime.Now;
            menu.UpdateName = "李四";
            menu.UpdateTime = DateTime.Now;
            var exist = _menuRepository.GetAll().Any(x => x.MenuName == request.MenuName && x.MenuId != request.MenuId && x.IsDel == 0);
            if (exist)
            {
                result.Code = APIEnum.AddFail;
                result.Message = APIEnum.AddFail.Desc() + "名称不能重复，请重新输入";
                return await Task.FromResult(result);
            }
            await _menuRepository.Update(menu);
            return await Task.FromResult(result);
        }
    }
}
